package dpe;

import java.util.ArrayList;

import org.lwjgl.input.Mouse;

import static org.lwjgl.opengl.GL11.*;

public class World {
	public Game game;
	private String name;
	private ArrayList<GameObject> objects = new ArrayList<GameObject>();
	private Player currentPlayer;
	private Camera currentCamera;

	public World(Game game, String name) {
		this.game = game;
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void addObject(GameObject object) {
		for (int i = 0; i < objects.size(); i++) {
			if (objects.get(i).getName().toLowerCase().equals(object.getName())) {
				Engine.log(2, "Could not add world '" + object.getName() + "': Two objects with the same name");
				Engine.exit(1);
			}
		}
		objects.add(object);
		Engine.log(0, "Added object '" + object.getName() + "' to World '" + name + "'");
	}

	public void update() {
		for (int i = 0; i < objects.size(); i++) {
			objects.get(i).update();
		}
		if (currentPlayer != null) {
			currentPlayer.update();
			currentCamera.setPos(currentPlayer.getPos());
			currentCamera.setRot(currentPlayer.getRot());
		}
	}

	public void render() {
		for (int i = 0; i < objects.size(); i++) {
			glLoadIdentity();
			if (currentCamera != null){
				currentCamera.translate();
			}
			objects.get(i).render();
		}
	}

	public void setPlayer(String name) {
		for (int i = 0; i < objects.size(); i++) {
			if (objects.get(i).getName().toLowerCase().equals(name)) {
				if (objects.get(i) instanceof Player) {
					currentPlayer = (Player) objects.get(i);
					Engine.log(0, "Player in world '" + this.name +"' set to '" + name + "'");
					return;
				}
			}
		}
		Engine.log(2, "Could not find player '" + name + "'");
		Engine.exit(1);
	}

	public void setCamera(String name) {
		for (int i = 0; i < objects.size(); i++) {
			if (objects.get(i).getName().toLowerCase().equals(name)) {
				if (objects.get(i) instanceof Camera) {
					currentCamera = (Camera) objects.get(i);
					Engine.log(0, "Camera in world '" + this.name +"' set to '" + name + "'");
					return;
				}
			}
		}
		Engine.log(2, "Could not find camera '" + name + "'");
		Engine.exit(1);
	}

}
